package com.example.springblog.controller;

import com.example.springblog.model.BlogInfo;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.BlogService;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JwtUtils;
import com.example.springblog.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName, String password){
        /**
         * 参数校验
         * 密码校验
         * 生成token 并返回
         */
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空");
        }
        //获取数据库中的密码
        UserInfo userInfo = userService.queryByName(userName);
        if(userInfo == null || userInfo.getId() < 0){
            return Result.fail("用户不存在");
        }
//        if(!password.equals(userInfo.getPassword())){
//            return Result.fail("密码错误!");
//        }
        boolean isOk = SecurityUtils.verify(password,userInfo.getPassword());
        if(!isOk){
            return Result.fail("密码错误!");
        }
        //生成token
        Map<String,Object> claim = new HashMap<>();
        claim.put("id",userInfo.getId());
        claim.put("name",userInfo.getUserName());
        String token = JwtUtils.genToken(claim);
        return Result.success(token);
    }

    //获取登录用户的信息
    @RequestMapping("/getUserInfo")
    public UserInfo userInfo(HttpServletRequest request){
        //1.从token 中获取用户Id
        //2.根据用户Id 获取用户信息
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId == null){
            return null;
        }
        return userService.queryById(userId);
    }

    //获取当前作者的信息
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId == null && blogId < 0){
            return null;
        }
        return userService.getAuthorInfo(blogId);
    }

    //发布博客

}
